package com.northone.statistics.activity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.northone.statistics.MyApplication;
import com.northone.statistics.R;
import com.northone.statistics.adapter.WeekPageAdapter;
import com.northone.statistics.database.SaintDataBaseHelper;
import com.northone.statistics.doman.WeekData;
import com.northone.statistics.fragment.WeekFourFragment;
import com.northone.statistics.fragment.WeekFragment;
import com.northone.statistics.fragment.WeekOneFragment;
import com.northone.statistics.fragment.WeekThreeFragment;
import com.northone.statistics.fragment.WeekTwoFragment;
import com.northone.statistics.utils.Constans;

import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MonthDataActivity extends FragmentActivity implements OnClickListener {
	private MyApplication application;
	private String clickMonth;
	private int clickPosition;
	private boolean isExist = false;
	public boolean isUpdate = false;
	private List<WeekFragment> week_fragments;
	public LinkedList<WeekData> weekDatas;  //用于存储用户输入周数据的List 。
	public List<WeekData> weeks;		//用于存储进入本界面时查询数据库中周数据的List 。

	private int normalNumber, baptismNumber, morningRiseNumber, prayNumber, gospelerNumber, familyMettNumber,
			rankMeetNumber, sundayMeetNumber;
	public ViewPager vp_week;
	private Cursor week_cursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_month_statis);
		application = (MyApplication) getApplication();
		// 获取用户点击的item的月份,和点击的位置 。
		clickMonth = getIntent().getStringExtra("month").replaceAll(" +", "");
		clickPosition = getIntent().getIntExtra(Constans.CLICK_POSITION, -1);
		
		if (clickPosition == -1) {
			clickPosition = Constans.getPositByName(clickMonth);
			
			weeks = new ArrayList<WeekData>();
			
			week_cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_MONTH_OF_WEEK, null, "month=?",
					new String[] { clickMonth }, null, null, null);
			boolean flag = week_cursor.moveToFirst();
			while (flag) {
				WeekData data = new WeekData();
				String month = week_cursor.getString(week_cursor.getColumnIndex("month"));
				data.weekm = week_cursor.getInt(week_cursor.getColumnIndex("week"));
				data.normalNum = week_cursor.getInt(week_cursor.getColumnIndex("normalNum"));
				data.baptismNum = week_cursor.getInt(week_cursor.getColumnIndex("baptismNum"));
				data.morningRiseNum = week_cursor.getInt(week_cursor.getColumnIndex("morningRiseNum"));
				data.prayNum = week_cursor.getInt(week_cursor.getColumnIndex("prayNum"));
				data.gospelerNum = week_cursor.getInt(week_cursor.getColumnIndex("gospelerNum"));
				data.familyMettNum = week_cursor.getInt(week_cursor.getColumnIndex("familyMettNum"));
				data.rankMeetNum = week_cursor.getInt(week_cursor.getColumnIndex("rankMeetNum"));
				data.sundayMeetNum = week_cursor.getInt(week_cursor.getColumnIndex("sundayMeetNum"));

				weeks.add(data);
				System.out.println(month + ",第" + data.weekm + "周 正常聚会" + data.normalNum + "人");
				flag = week_cursor.moveToNext();
			}
			isUpdate = true;
		}

		Cursor cursor = application.database.query(SaintDataBaseHelper.TABLE_NAME_MONTH_ITEM, new String[] { "month" },
				null, null, null, null, null);

		boolean flag = cursor.moveToFirst();
		while (flag) {
			String month = cursor.getString(cursor.getColumnIndex("month"));
			if (!TextUtils.isEmpty(month) && clickMonth.equals(month)) {
				isExist = true;
				break;
			}
			flag = cursor.moveToNext();
		}
		initTitleBar();
		initWeekFragment();
		initView();
		
		
		if (cursor != null)
			cursor.close();
	}

	/** 初始化标题栏 。 */
	private void initTitleBar() {
		ImageView iv_back = (ImageView) findViewById(R.id.iv_lefticon);
		iv_back.setImageResource(R.drawable.addsaint_titlebar_back_selector);
		iv_back.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.tv_title);
		title.setText(clickMonth + "份数据");
		Button btn_submit = (Button) findViewById(R.id.btn_submit);
		btn_submit.setText("确定");
		btn_submit.setVisibility(View.VISIBLE);
		btn_submit.setOnClickListener(this);
	}

	/** 初始化月中周的Fragment 。 */
	private void initWeekFragment() {
		vp_week = (ViewPager) findViewById(R.id.vp_week);

		week_fragments = new ArrayList<WeekFragment>();
		weekDatas = new LinkedList<WeekData>();

		week_fragments.add(new WeekOneFragment());
		week_fragments.add(new WeekTwoFragment());
		week_fragments.add(new WeekThreeFragment());
		week_fragments.add(new WeekFourFragment());
	}

	private void initView() {
		vp_week.setAdapter(new WeekPageAdapter(getSupportFragmentManager(), week_fragments));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_lefticon:
			finish();
			break;
		case R.id.btn_submit:
			submitMonthInfo();
			break;
		default:
			break;
		}
	}

	private void submitMonthInfo() {
		int weeksSize = weekDatas.size();
		if (weeksSize < 1) {
			Toast.makeText(this, "请输入每周的数据并保存 !", Toast.LENGTH_LONG).show();
			return;
		}

		for (int i = 0; i < weeksSize; i++) {
			WeekData data = weekDatas.get(i);
			if (data != null) {
				int normalNum = data.normalNum;
				int baptismNum = data.baptismNum;
				int morningRiseNum = data.morningRiseNum;
				int prayNum = data.prayNum;
				int gospelerNum = data.gospelerNum;
				int familyMettNum = data.familyMettNum;
				int rankMeetNum = data.rankMeetNum;
				int sundayMeetNum = data.sundayMeetNum;

				ContentValues values = new ContentValues();
				values.put("month", clickMonth);
				values.put("week", i);
				values.put("normalNum", normalNum);
				values.put("baptismNum", baptismNum);
				values.put("morningRiseNum", morningRiseNum);
				values.put("prayNum", prayNum);
				values.put("gospelerNum", gospelerNum);
				values.put("familyMettNum", familyMettNum);
				values.put("rankMeetNum", rankMeetNum);
				values.put("sundayMeetNum", sundayMeetNum);

				try {
					if (weeks != null && i == weeks.get(i).weekm) {
						application.database.update(SaintDataBaseHelper.TABLE_NAME_MONTH_OF_WEEK, values, "month=? AND week=?",
								new String[] { clickMonth,String.valueOf(i) });
						System.out.println("update : " + i + "周");
					} else {
						application.database.insert(SaintDataBaseHelper.TABLE_NAME_MONTH_OF_WEEK, null, values);
						System.out.println("insert : " + i + "周");
					}
				} catch (IndexOutOfBoundsException e) {
					application.database.insert(SaintDataBaseHelper.TABLE_NAME_MONTH_OF_WEEK, null, values);
					System.out.println("insert : " + i + "周");
				}

				normalNumber += normalNum;
				baptismNumber += baptismNum;
				morningRiseNumber += morningRiseNum;
				prayNumber += prayNum;
				gospelerNumber += gospelerNum;
				familyMettNumber += familyMettNum;
				rankMeetNumber += rankMeetNum;
				sundayMeetNumber += sundayMeetNum;
			}
		}

		ContentValues values = new ContentValues();
		values.put("month", clickMonth);
		values.put("orderBy", clickPosition);
		values.put("normalNum", "正常聚会" + normalNumber / weeksSize + "人");
		values.put("baptismNum", "受浸" + baptismNumber + "人");
		values.put("morningRiseNum", "晨兴" + morningRiseNumber / weeksSize + "人");
		values.put("prayNum", "参加祷告聚会" + prayNumber / weeksSize + "人");
		values.put("gospelerNum", "传福音" + gospelerNumber / weeksSize + "人");
		values.put("familyMettNum", "家聚会" + familyMettNumber + "次");
		values.put("rankMeetNum", "排聚会" + rankMeetNumber + "次");
		values.put("sundayMeetNum", "参加主日聚会" + sundayMeetNumber / weeksSize + "人");

		if (isExist) {
			application.database.update(SaintDataBaseHelper.TABLE_NAME_MONTH_ITEM, values, "month=?",
					new String[] { clickMonth });
			System.out.println("update::" + clickMonth);
		} else {
			application.database.insert(SaintDataBaseHelper.TABLE_NAME_MONTH_ITEM, null, values);
			System.out.println("insert::" + clickMonth);
		}

		setResult(RESULT_OK);

		finish();
	}
}
